package com.vgulu.server.common.utils;
import com.vgulu.server.common.TConstant;
import okhttp3.*;
import okhttp3.logging.HttpLoggingInterceptor;


import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
 * Created by wangchunsee on 2017/1/22.
 */
public class OKHttpUtil {



    private static OkHttpClient okHttpClient;
    static {
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.NONE);
//        CookieJar oCookieJar = new CookieJar() {
//            private final Set<Cookie> aCookies = new HashSet<Cookie>();
//            @Override
//            public void saveFromResponse(HttpUrl oHttpUrl, List<Cookie> aCookiesList)
//            {
//                if (oHttpUrl.host().equalsIgnoreCase("sx.hiido.com")){
//                    return ;
//                }
//                aCookies.addAll(aCookiesList);
//            }
//            @Override
//            public List<Cookie> loadForRequest(HttpUrl oHttpUrl)
//            {
//                if (oHttpUrl.host().equalsIgnoreCase("sx.hiido.com")){
//                    return new ArrayList<>();
//                }
//                return new ArrayList<Cookie>(aCookies);
//            }
//        };

        okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(interceptor)
//                .cookieJar(oCookieJar)
                .readTimeout(35, TimeUnit.SECONDS)
                .connectTimeout(10, TimeUnit.SECONDS)
                .build();

    }

    public static String get(String url) throws IOException {
        Request request = new Request.Builder().url(url).build();
        Response rsp = okHttpClient.newCall(request).execute();
        byte[] str = rsp.body().bytes();
        String ct = rsp.header("Content-Type");
        String charSet=parseCharset(ct);
        String temp = new String(str,charSet);
        return temp;
    }

    public static String get(String url,List<NameValuePair> nvps) throws IOException {
        String realUrl = smartUrl(url,nvps,false);
        Request request = new Request.Builder().url(realUrl).build();
        Response rsp = okHttpClient.newCall(request).execute();
//        byte[] str = rsp.body().bytes();
//        String ct = rsp.header("Content-Type");
//        String charSet=parseCharset(ct);
//        String temp = new String(str,charSet);
        return rsp.body().string();
    }

    public static String postJson(String url,Object o) throws IOException {
        return post(url, TConstant.gson.toJson(o),"application/json; charset=utf-8");
    }

    public static String post(String url,String content,String mediaType) throws IOException {
        RequestBody body = RequestBody.create(MediaType.parse(mediaType),content);
        Request request = new Request.Builder().url(url).post(body).build();
        Response rsp = okHttpClient.newCall(request).execute();
        byte[] str = rsp.body().bytes();
        String ct = rsp.header("Content-Type");
        String charSet=parseCharset(ct);
        String temp = new String(str,charSet);
        return temp;
    }

    public static String post(String url,List<NameValuePair> nvps) throws IOException {
        FormBody.Builder builder = new FormBody.Builder();
        for (NameValuePair nv : nvps){
            builder.add(nv.getName(),nv.getValue());
        }
        Request request = new Request.Builder().url(url).post(builder.build()).build();
        Response rsp = okHttpClient.newCall(request).execute();
        byte[] str = rsp.body().bytes();
        String ct = rsp.header("Content-Type");
        String charSet=parseCharset(ct);
        String temp = new String(str,charSet);
        return temp;
    }


    public static String smartUrl(String url,List<NameValuePair> nvps,boolean encoded) {
        if (nvps==null||nvps.isEmpty()){
            return url;
        }
        boolean first = !url.contains("?");
        StringBuilder builder = new StringBuilder();
        builder.append(url);
        String charset = "UTF-8";
        try {
            for (NameValuePair nv : nvps){
                if (first){
                    builder.append("?");
                    first=false;
                }else {
                    builder.append("&");
                }
                if (encoded){
                    builder.append(nv.getName());
                    builder.append("=");
                    builder.append(nv.getValue());
                }else {
                    builder.append(URLEncoder.encode(nv.getName(),charset));
                    builder.append("=");
                    builder.append(URLEncoder.encode(nv.getValue(),charset));
                }
            }
            return builder.toString();
        }catch (Throwable e){
            throw new RuntimeException(e);
        }

    }

    public static String parseCharset(String meta) {
        Pattern pattern = Pattern.compile("charset(\\S*?)=(\\S*?)\"?[^\"]*\"");
        Matcher matcher = pattern.matcher(meta);
        if (matcher.find()) {
            String temp = matcher.group(0);
            String[] arr = temp.split("=");
            String charset = arr[1].trim().toUpperCase();
            if (charset.startsWith("\"")) {
                charset = charset.substring(1).trim();
            }
            StringBuilder builder = new StringBuilder(charset.length());
            int n = charset.length();
            int i = 0;
            for (; i < n; i++) {
                char c = charset.charAt(i);
                if (c >= 'A' && c <= 'Z') continue;
                if (c >= 'a' && c <= 'z') continue;
                if (c >= '0' && c <= '9') continue;
                if (c == '-' && i != 0) continue;
                if (c == '+' && i != 0) continue;
                if (c == ':' && i != 0) continue;
                if (c == '_' && i != 0) continue;
                if (c == '.' && i != 0) continue;
                break;
            }
            String sub = charset.substring(0, i);
            return sub;
        }
        return "utf-8";
    }


    public static class NameValuePair{
        private String name;
        private String value;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getValue() {
            return value;
        }

        public void setValue(String value) {
            this.value = value;
        }
    }

}
